import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path/path.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:zootix/models/zt_im_message.model.dart';
import 'package:zootix/screens/chat/zt_private_chat.controller.dart';
import 'package:zootix/screens/chat/zt_private_message_file_preview.dart';
import 'package:zootix/services/zt_translate.service.dart';
import 'package:zootix/store/zt_auth.store.dart';
import 'package:zootix/util/zt_screen_adaper_util.dart';
import 'package:zootix/widgets/zt_fade_in_cache_image.dart';
import 'package:zootix/zt_app_theme.dart';

class ZtPrivateMessageItem extends StatelessWidget {
  final _controller = Get.find<ZtPrivateChatController>();
  late ZtIMessageModel chatModel;
  late int index;
  ZtPrivateMessageItem(
      {super.key, required this.chatModel, required this.index}) {}
  @override
  Widget build(BuildContext context) {
    bool isMe = chatModel.userId == ZtAuthStore.to.userInfo.value.userId;
    return Column(children: [
      if (chatModel.sentDay != null)
        Container(
          margin: EdgeInsets.symmetric(
            vertical: ZtScreenAdaper.height(30),
          ),
          child: Text(
            '${chatModel.sentDay}',
            style: TextStyle(
                color: const Color(0xFF000000).withOpacity(0.3),
                fontSize: ZtScreenAdaper.sp(15)),
          ),
        ),
      !isMe
          ? Container(
              padding: EdgeInsets.symmetric(
                  horizontal: ZtScreenAdaper.width(10),
                  vertical: ZtScreenAdaper.height(5)),
              child: Row(
                children: [
                  SizedBox(
                    width: ZtScreenAdaper.width(40),
                    height: ZtScreenAdaper.width(40),
                    child: ClipOval(
                        child: _controller.isCustomerService
                            ? Container(
                                decoration:
                                    BoxDecoration(color: Colors.grey[400]),
                                child: Image(
                                    height: ZtScreenAdaper.height(40),
                                    width: ZtScreenAdaper.width(40),
                                    image: const AssetImage(
                                        'assets/images/customer_servicer.png')))
                            : ZtFadeInCacheImage(
                                url: Get.arguments['avatar'] ??
                                    chatModel.avatarUrl!,
                              )),
                  ),
                  SizedBox(
                    width: ZtScreenAdaper.width(10),
                  ),
                  chatModel.type == RCIMIWMessageType.voice
                      ? _buildVoiceMessage(chatModel: chatModel, isMe: isMe)
                      : chatModel.type == RCIMIWMessageType.image
                          ? _buildImageMessage(chatModel: chatModel, isMe: isMe)
                          : chatModel.type == RCIMIWMessageType.file
                              ? _buildFileMessage(
                                  chatModel: chatModel, isMe: isMe)
                              : Stack(
                                  children: [
                                    Container(
                                      constraints: BoxConstraints(
                                          maxWidth:
                                              ZtScreenAdaper.screenHeight() /
                                                  3),
                                      margin: EdgeInsets.symmetric(
                                          vertical: ZtScreenAdaper.height(8)),
                                      decoration: BoxDecoration(
                                          color: Colors.white,
                                          borderRadius: BorderRadius.circular(
                                              ZtScreenAdaper.sp(12))),
                                      padding: EdgeInsets.symmetric(
                                          horizontal: ZtScreenAdaper.width(10),
                                          vertical: ZtScreenAdaper.height(10)),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Text(
                                            chatModel.content ?? '',
                                            style: TextStyle(
                                                fontSize: ZtScreenAdaper.sp(14),
                                                fontWeight: FontWeight.w500),
                                          ),
                                          if (chatModel.translatedText != null)
                                            const Divider(),
                                          if (chatModel.translatedText != null)
                                            Text(
                                              chatModel.translatedText ?? '',
                                              style: TextStyle(
                                                  fontSize:
                                                      ZtScreenAdaper.sp(14),
                                                  fontWeight: FontWeight.w500),
                                            ),
                                        ],
                                      ),
                                    ),
                                    if (ZtTranslateService
                                        .to.autoTranslate.value)
                                      Positioned(
                                          bottom: 0,
                                          right: 0,
                                          child: InkWell(
                                            onTap: () async {
                                              await _controller
                                                  .translateMessage(
                                                      chatModel.content ?? '',
                                                      index);
                                            },
                                            child: Stack(
                                              alignment: Alignment.topCenter,
                                              children: [
                                                chatModel.translatedText != null
                                                    ? const SizedBox()
                                                    : chatModel.isTranslating
                                                        ? const CupertinoActivityIndicator()
                                                        : Image(
                                                            height:
                                                                ZtScreenAdaper
                                                                    .height(20),
                                                            image: const AssetImage(
                                                                'assets/images/translate_btn.png')),
                                                Positioned(
                                                    top: 0,
                                                    bottom: 0,
                                                    child: Text(
                                                      ZtTranslateService
                                                          .to.languageCode.value
                                                          .toUpperCase(),
                                                      style: TextStyle(
                                                          color: Colors.white,
                                                          fontSize:
                                                              ZtScreenAdaper.sp(
                                                                  12)),
                                                    ))
                                              ],
                                            ),
                                          )),
                                  ],
                                ),
                ],
              ),
            )
          : Container(
              padding: EdgeInsets.symmetric(
                  horizontal: ZtScreenAdaper.width(10),
                  vertical: ZtScreenAdaper.height(5)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  chatModel.sentStatus == RCIMIWSentStatus.sending
                      ? const CupertinoActivityIndicator()
                      : chatModel.sentStatus == RCIMIWSentStatus.failed
                          ? const Icon(
                              Icons.error_sharp,
                              color: Colors.red,
                            )
                          : const SizedBox(),
                  SizedBox(
                    width: ZtScreenAdaper.width(5),
                  ),
                  chatModel.type == RCIMIWMessageType.voice
                      ? _buildVoiceMessage(chatModel: chatModel, isMe: isMe)
                      : chatModel.type == RCIMIWMessageType.image
                          ? _buildImageMessage(chatModel: chatModel, isMe: isMe)
                          : chatModel.type == RCIMIWMessageType.file
                              ? _buildFileMessage(
                                  chatModel: chatModel, isMe: isMe)
                              : Container(
                                  margin: EdgeInsets.symmetric(
                                      vertical: ZtScreenAdaper.height(8)),
                                  constraints: BoxConstraints(
                                      maxWidth:
                                          ZtScreenAdaper.screenHeight() / 3),
                                  decoration: BoxDecoration(
                                      color: const Color(0xFFABEF1C),
                                      borderRadius: BorderRadius.circular(
                                          ZtScreenAdaper.sp(12))),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: ZtScreenAdaper.width(10),
                                      vertical: ZtScreenAdaper.height(10)),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        chatModel.content ?? '',
                                        style: TextStyle(
                                            color: const Color(0xFFFFFFFF),
                                            fontSize: ZtScreenAdaper.sp(14),
                                            fontWeight: FontWeight.w500),
                                      ),
                                    ],
                                  ),
                                ),
                  SizedBox(
                    width: ZtScreenAdaper.width(10),
                  ),
                  SizedBox(
                    width: ZtScreenAdaper.width(40),
                    height: ZtScreenAdaper.width(40),
                    child: ClipOval(
                      child: ZtFadeInCacheImage(
                        url: ZtAuthStore.to.userInfo.value.avatarThumbUrl,
                      ),
                    ),
                  ),
                ],
              ),
            )
    ]);
  }

  Widget _buildVoiceMessage(
      {required ZtIMessageModel chatModel, bool isMe = false}) {
    String? url = chatModel.content?.replaceFirst('http://', 'https://');
    return GetBuilder<ZtPrivateChatController>(builder: (_) {
      return InkWell(
        onTap: () {
          _controller.mPlayer!.isPlaying
              ? _controller.stopPlayer()
              : _controller.playVoiceMessage(url);
        },
        child: !isMe
            ? Row(children: [
                Container(
                    width: ZtScreenAdaper.width(110),
                    margin: EdgeInsets.symmetric(
                        vertical: ZtScreenAdaper.height(8),
                        horizontal: ZtScreenAdaper.width(8)),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius:
                            BorderRadius.circular(ZtScreenAdaper.sp(12))),
                    padding: EdgeInsets.symmetric(
                        horizontal: ZtScreenAdaper.width(6),
                        vertical: ZtScreenAdaper.height(6)),
                    child: Row(
                      children: [
                        Image(
                            height: ZtScreenAdaper.height(25),
                            image: AssetImage(
                                'assets/images/target_${_controller.mPlayer!.isPlaying && _controller.playingUrl == url ? 'pause' : 'play'}_icon.png')),
                        SizedBox(
                          width: ZtScreenAdaper.width(10),
                        ),
                        Image(
                            height: ZtScreenAdaper.height(25),
                            image: const AssetImage(
                                'assets/images/target_voice_icon.png')),
                      ],
                    )),
                SizedBox(
                  width: ZtScreenAdaper.width(5),
                ),
                if (_controller.isLoadingVoice.value &&
                    _controller.playingUrl == url)
                  const CupertinoActivityIndicator(),
              ])
            : Row(
                children: [
                  if (_controller.isLoadingVoice.value &&
                      _controller.playingUrl == url)
                    const CupertinoActivityIndicator(),
                  SizedBox(
                    width: ZtScreenAdaper.width(5),
                  ),
                  Container(
                      width: ZtScreenAdaper.width(110),
                      margin: EdgeInsets.symmetric(
                          vertical: ZtScreenAdaper.height(8),
                          horizontal: ZtScreenAdaper.width(8)),
                      decoration: BoxDecoration(
                          color: const Color(0xFFABEF1C),
                          borderRadius:
                              BorderRadius.circular(ZtScreenAdaper.sp(12))),
                      padding: EdgeInsets.symmetric(
                          horizontal: ZtScreenAdaper.width(6),
                          vertical: ZtScreenAdaper.height(6)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Image(
                              height: ZtScreenAdaper.height(25),
                              image: AssetImage(
                                  'assets/images/my_${_controller.mPlayer!.isPlaying && _controller.playingUrl == url ? 'pause' : 'play'}_icon.png')),
                          SizedBox(
                            width: ZtScreenAdaper.width(10),
                          ),
                          Image(
                              height: ZtScreenAdaper.height(25),
                              image: const AssetImage(
                                  'assets/images/my_voice_icon.png'))
                        ],
                      ))
                ],
              ),
      );
    });
  }

  Widget _buildImageMessage(
      {required ZtIMessageModel chatModel, bool isMe = false}) {
    return chatModel.content != null
        ? ZtFadeInCacheImage(
            width: ZtScreenAdaper.screenWidth() / 2,
            url: chatModel.content,
          )
        : [RCIMIWSentStatus.sending, RCIMIWSentStatus.failed]
                .contains(chatModel.sentStatus)
            ? (chatModel.filePath != null
                ? Image.file(
                    File(chatModel.filePath!),
                    width: ZtScreenAdaper.screenWidth() / 2,
                  )
                : SizedBox())
            : SizedBox();
  }

  Widget _buildFileMessage(
      {required ZtIMessageModel chatModel, bool isMe = false}) {
    return InkWell(
      onTap: () {
        Get.to(ZtPrivateMessageFilePreview(
            filename: chatModel.filename!, url: chatModel.content!));
      },
      child: Container(
        constraints: BoxConstraints(maxWidth: ZtScreenAdaper.width(150)),
        padding: EdgeInsets.symmetric(
            horizontal: ZtScreenAdaper.width(10),
            vertical: ZtScreenAdaper.height(10)),
        decoration: BoxDecoration(
            color: !isMe ? Colors.white : ZtAppTheme.primaryColor,
            borderRadius: BorderRadius.circular(10)),
        child: Column(children: [
          Icon(
            Icons.file_copy_outlined,
            color: !isMe ? Colors.black : ZtAppTheme.white,
            size: ZtScreenAdaper.sp(30),
          ),
          SizedBox(
            height: ZtScreenAdaper.height(5),
          ),
          Text(
            '${chatModel.filename}',
            style: TextStyle(
                color: !isMe ? Colors.grey[500] : ZtAppTheme.white,
                fontSize: ZtScreenAdaper.sp(15),
                fontWeight: FontWeight.w500),
          )
        ]),
      ),
    );
  }
}
